//
//  AppDelegate.m
//  GolfFriend
//
//  Created by vescky on 13-11-24.
//  Copyright (c) 2013年 vescky.org. All rights reserved.
//

#import "AppDelegate.h"
#import "AppsLocationManager.h"
#import "GFVOs.h"
#import "GFVOParser.h"
#import "WeatherGetter.h"
#import "DateUtility.h"
#import "UserPublicInfoVO.h"
#import "APService.h"
#import "UserSession.h"
#import "AppsEngine.h"
#import "ChatDAO.h"
#import "ContactBook.h"
#import "SVProgressHUD.h"


//#define TEST_MODE @"LoginPageViewController"


@implementation AppDelegate

@synthesize photoAlbumSelectedArray,imageUpoadQueueDelegate;

static bool uploadDone,isUploadQueueBusy;
int backgroundCounter,retryCounter;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    [self initNavigationController];
    [self initApp];
    [self startJPushService:launchOptions];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userLocationUpdated) name:Notification_Location_Updated object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(userDidLogout) name:Notification_user_logout object:nil];
    
    //解决MKNetWork无网络解锁闪退的bug
    signal(SIGPIPE, SIG_IGN);
    
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    
    if (isUploadQueueBusy) {
        [self beingBackgroundUpdateTask];
    }
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    [application setApplicationIconBadgeNumber:0];//清空图标
    [self endBackgroundUpdateTask];
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [APService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *) error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [APService handleRemoteNotification:userInfo];
}

//avoid compile error for sdk under 7.0
//For iOS7，收到推送后，可以后台获取通知的内容
#ifdef __IPHONE_7_0
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNoData);
}
#endif


#pragma mark - Private 
- (void)initNavigationController {       
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.hpViewController = [[HomePage2ViewController alloc] initWithNibName:@"HomePage2ViewController" bundle:nil];
    self.loginViewController = [[LoginPageViewController alloc] initWithNibName:@"LoginPageViewController" bundle:nil];
    
    self.sideBarViewController = [[SideBarViewController alloc] initWithNibName:@"SideBarViewController" bundle:nil];
    self.sidePannelController = [[JASidePanelController alloc] init];
    self.sidePannelController.centerPanel = self.hpViewController;
    self.sidePannelController.leftPanel = self.sideBarViewController;
    self.sidePannelController.allowRightOverpan = NO;
    
    self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.sidePannelController];
#ifdef TEST_MODE
    Class viewClass = NSClassFromString(TEST_MODE);
    self.tViewController = [[viewClass alloc] init];
    self.navigationController = [[UINavigationController alloc] initWithRootViewController:self.tViewController];
#endif
    [self.navigationController.navigationBar setHidden:YES];
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
//        [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"titlebar_bg.png"] forBarMetrics:UIBarMetricsDefault];
    }
    
    //    self.navigationController.navigationItem.rightBarButtonItem = backItem;
    
    self.window.rootViewController = self.navigationController;
    
    [self.window makeKeyAndVisible];
    
#if ShowToolbarInWindow == 1
    self.gfToolbar = [[ToolbarViewController alloc] init];
    CGRect gfToolbarFrame = self.gfToolbar.view.frame;
    gfToolbarFrame.origin.y = self.window.frame.size.height - gfToolbarFrame.size.height;
    self.gfToolbar.view.frame = gfToolbarFrame;
    if (ShowToolbarInWindow) {
        [self.window addSubview:self.gfToolbar.view];
    }
#endif
    
}

- (void)initApp {
    [self startBaiduMapServices];
    [self startGetWeather];
    [self checkIfLogined];
    [self refreshContactBook];
    [self getMessagesFromServerOnBackground];
    [self checkNewVersion:NO];
    if (ios7OrLater) {
        [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    }
    
    imageUploaderSerialQueue = [ImageUploader shareImageUploader];
    imageUploaderSerialQueue.delegate = self;
    
    arrForFialToUploadImages = [[NSMutableArray alloc] init];
    photoAlbumSelectedArray = [[NSMutableArray alloc] init];
}

- (void)startBaiduMapServices {
//    _mapManager = [[BMKMapManager alloc]init];
//    dispatch_queue_t queue = dispatch_queue_create("startBaiduMapServices", NULL);
//    dispatch_async(queue, ^{
//        BOOL ret = [_mapManager start:@"nLTjxKmjxrMiGBtwVxr5DrL9" generalDelegate:nil];
//        if (!ret) {
//            NSLog(@"\n\n\n ================== BMKMapManager start failed! ==================== \n\n\n");
//        }
//        else {
            [[AppsLocationManager sharedManager] startUpdate];
//        }
//    });
}

- (void)startGetWeather {
    NSUserDefaults *usd = [NSUserDefaults standardUserDefaults];
    if (![usd objectForKey:@"weatherInfo"]) {
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:@"广州",@"cityName",@"guangzhou",@"cityNameEn",
                              @"20",@"currentTemp",@"晴",@"currentWeather",@"sunny.png",@"currentWeatherIcon",nil];
        [usd setObject:dict forKey:@"weatherInfo"];
    }
    dispatch_queue_t queue = dispatch_queue_create("startBaiduMapServices", NULL);
    dispatch_async(queue, ^{
        WetherInfoVO *weatherVo = [[WeatherGetter shareWeatherGetter] refreshWeather];
        NSDictionary *dict = [weatherVo toDictionary];
        NSLog(@"dict:%@",dict);
        if (dict) {
            [usd setObject:dict forKey:@"weatherInfo"];    
            //发送天气更新的通知
            [[NSNotificationCenter defaultCenter] postNotificationName:@"WeatherForcast" object:dict];
        }
    });
    
}

- (void)startJPushService:(NSDictionary *)launchOptions {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    
    [defaultCenter addObserver:self selector:@selector(networkDidSetup:) name:kAPNetworkDidSetupNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidClose:) name:kAPNetworkDidCloseNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidRegister:) name:kAPNetworkDidRegisterNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidLogin:) name:kAPNetworkDidLoginNotification object:nil];
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kAPNetworkDidReceiveMessageNotification object:nil];
    
    [self.window makeKeyAndVisible];
    
    [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                   UIRemoteNotificationTypeSound |
                                                   UIRemoteNotificationTypeAlert)];
    [APService setupWithOption:launchOptions];
    //设置推送别名
//    NSString *aliasString = [NSString stringWithFormat:@"gfUser_%@",[OpenUDID value]];
    [APService setAlias:GetToken_Alias callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
    
//    [APService setTags:[NSSet setWithObjects:@"tag1", @"tag2", @"tag3", nil] alias:@"别名"];
    
//    [APService setTags:[NSSet setWithObjects:@"tag4",@"tag5",@"tag6",nil] alias:@"别名" callbackSelector:@selector(tagsAliasCallback:tags:alias:) object:self];
}

//用户位置更新
- (void)userLocationUpdated {
    [self doLogin];
    [self startGetWeather];
    self.userCurrentLocation = [[AppsLocationManager sharedManager] currentLocation];
}

- (void)checkIfLogined {
    //检查是否登录
    if (![[UserSession shareUserSession] isLoginned]) {
        LoginPageViewController *lgVc = [[LoginPageViewController alloc] initWithNibName:@"LoginPageViewController" bundle:nil];
        [self.navigationController pushViewController:lgVc animated:YES];
    }
}

- (void)refreshContactBook {
//    NSMutableArray *friendList = [[[[UserSession shareUserSession] getUserPrivateInfo] objectForKey:@"friendList"] objectForKey:@"default"];
//    NSMutableArray *blackList = [[[[UserSession shareUserSession] getUserPrivateInfo] objectForKey:@"blackList"] objectForKey:@"default"];
//    
//    for (int i = 0; i < [friendList count]; i = i + 20) {
//        if ([friendList count] <= 20) {
//            
//        }
//    }
    NSString *userId = [[UserSession shareUserSession] getUserId];
    if (!isValueSet(userId)) {
        return;
    }
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:userId,@"userId", nil];
    
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetFriendList" param:params onCompletion:^(id jsonResponse) {
        if (isValueSet([jsonResponse objectForKey:@"friendList"])) {
            NSMutableArray *fArr = [[NSMutableArray alloc] initWithArray:[jsonResponse objectForKey:@"friendList"]];
            [[ContactBook shareContactBook] saveFriendList:fArr];
        }
        if (isValueSet([jsonResponse objectForKey:@"blackList"])) {
            NSMutableArray *bArr = [[NSMutableArray alloc] initWithArray:[jsonResponse objectForKey:@"blackList"]];
            [[ContactBook shareContactBook] saveBlackList:bArr];
        }
    } onError:^(NSError *error) {
        NSLog(@"get friend list failed!");
    } method:@"GET"];
    
}

- (void)doLogin {
    UserPrivateInfoVO *uPrivate = [[UserPrivateInfoVO alloc] init];
    [uPrivate dictionaryToUserPrivateInfoVO:[[UserSession shareUserSession] getUserPrivateInfo]];
    CLLocation *currentLocation = [[AppsLocationManager sharedManager] currentLocation];
    
    //刷新用户好友列表
    [self refreshContactBook];
    
    //发送登陆的请求
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:uPrivate.phone,@"phone",
                                 [[UserSession shareUserSession] getSmsCode],@"smsAuthCode",
                                 GetToken_Alias,@"token",
                                 [NSString stringWithFormat:@"%lf",currentLocation.coordinate.latitude],@"latitude",
                                 [NSString stringWithFormat:@"%lf",currentLocation.coordinate.longitude],@"longitude",nil];
    
    [[AppsEngine shareAppsEngine] submitRequest:@"gfUserLogin" param:dict onCompletion:^(id jsonResponse) {
        NSLog(@"登陆成功! %@",jsonResponse);
        NSDictionary *rDict = jsonResponse;
        if ([[rDict objectForKey:@"status"] isEqualToString:@"success"]) {
            UserSession *us = [UserSession shareUserSession];
            NSDictionary *prDict = [[[GFVOParser shareParser] parseDataForUserPrivateInfo:jsonResponse] toDictionary];
            NSDictionary *pbDict = [[[GFVOParser shareParser] parseDataForUserPublicInfo:jsonResponse] toDictionary];
            [us saveUserInfo:prDict];
            [us savePublicInfo:pbDict];
        }
    } onError:^(NSError *error) {
        NSLog(@"联网失败");
        //            DXAlertView *dAlert = [[DXAlertView alloc] initWithTitle:@"温馨提示" contentText:@"无网络连接!" leftButtonTitle:nil rightButtonTitle:@"确定"];
        //            [dAlert show];
    } method:@"GET"];
}

#pragma mark - JPush Delegate
- (void)networkDidSetup:(NSNotification *)notification {
    NSLog(@"已连接...");
}

- (void)networkDidClose:(NSNotification *)notification {
    NSLog(@"未连接...");
}

- (void)networkDidRegister:(NSNotification *)notification {
    NSLog(@"已注册...");
}

- (void)networkDidLogin:(NSNotification *)notification {
    NSLog(@"已登录...");
}


#pragma mark - Handle chat message
- (void)getMessagesFromServerOnBackground {
    if (self.isGettingMessage) {
        return;
    }
    NSString *userId = [[UserSession shareUserSession] getUserId];
    if (!isValueSet(userId)) {
        return;
    }
    self.isGettingMessage = YES;
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:userId,@"userId", nil];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfGetMessage" param:params onCompletion:^(id jsonResponse) {
        self.isGettingMessage = NO;
        if (isValueSet([jsonResponse objectForKey:@"content"])) {
           NSMutableArray *newMessagesArray = [[NSMutableArray alloc] initWithArray:[jsonResponse objectForKey:@"content"]];
            [self handleChatMessages:newMessagesArray];
        }
    } onError:^(NSError *error) {
        self.isGettingMessage = NO;
        
    } method:@"GET"];
}

- (void)handleChatMessages:(NSMutableArray*)msgArray {
    if (!isValueSet(msgArray)) {
        return;
    }
    for (int i = 0; i < [msgArray count]; i++) {
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithDictionary:[msgArray objectAtIndex:i]];
        [dict setObject:[dict objectForKey:@"id"] ? [dict objectForKey:@"id"] : @"1" forKey:@"msgId"];
        [dict removeObjectForKey:@"id"];
        [msgArray replaceObjectAtIndex:i withObject:dict];
    }
    //插入数据库
    [[ChatDAO shareChatDAO] saveMessages:msgArray];
    //获取陌生人的资料
    [self handleVisitorMessages:msgArray];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Chat_Recieved object:msgArray];
    
    UIViewController *vc = self.navigationController.topViewController;
    if ([vc isKindOfClass:NSClassFromString(@"OneToOneChatViewController")] || [vc isKindOfClass:NSClassFromString(@"ChatListViewController")]) {
        return;
    }
    else {
//        [self showMessageAlertOnStatusBar:[NSString stringWithFormat:@"新的消息(%d)",[msgArray count]]];
    }
    
    //has read message
    NSString *msgIdListString = combineArrayWithSeperator(msgArray, @",");
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:msgIdListString,@"msgID", nil];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfHasReadMessage" param:params onCompletion:^(id jsonResponse) {
        NSLog(@"has read message: -- %@",jsonResponse);
    } onError:^(NSError *error) {
        NSLog(@"send read message failed");
    } method:@"GET"];
    
}

- (void)handleVisitorMessages:(NSArray*)tArr {
    NSString *str = @"";
    for (int i = 0; i < [tArr count]; i++) {
        NSString *fId = [[tArr objectAtIndex:i] objectForKey:@"fromId"];
        if (isValueSet(fId) && ![[ContactBook shareContactBook] isFriendExist:fId]) {
            //陌生人
            str = [str stringByAppendingFormat:@"%@,",fId];
        }
    }
    if (str.length > 0) {
        NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:str,@"userIDs", nil];
        [[AppsEngine shareAppsEngine] submitRequest:@"gfGetUserInfo" param:params onCompletion:^(id jsonResponse) {
            NSArray *uList = [jsonResponse objectForKey:@"userInfoList"];
            if (isValueSet(uList)) {
                [[ContactBook shareContactBook] saveVisitorList:[[NSMutableArray alloc] initWithArray:uList]];
                //通讯录已更新
                [[NSNotificationCenter defaultCenter] postNotificationName:Notification_ContactBook_Refreshed object:nil];
            }
        } onError:^(NSError *error) {
            
        } method:@"GET"];
    }
}

- (void)showMessageAlertOnStatusBar:(NSString*)alertTitle {
    messageNotiView = [[UIView alloc] initWithFrame:CGRectMake(0,0, 80, 20)];
    messageNotiView.clipsToBounds = YES;
    messageNotiView.backgroundColor = [UIColor clearColor];
    
    UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(0, 5, 10, 10)];
    [imgv setImage:[UIImage imageNamed:@"comment_251.png"]];
    [messageNotiView addSubview:imgv];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, messageNotiView.frame.size.width - 10, messageNotiView.frame.size.height)];
    [label setText:alertTitle];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:10.0];
    label.lineBreakMode = NSLineBreakByTruncatingMiddle;
    label.textColor = GetColorWithRGB(251, 131, 52);
    [messageNotiView addSubview:label];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, messageNotiView.frame.size.width, messageNotiView.frame.size.height)];
    [btn setBackgroundColor:[UIColor clearColor]];
    [btn addTarget:self action:@selector(messageAlertViewOnStatusBarDidClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [messageNotiView addSubview:btn];
    
    if (ios7OrLater) {
        UIWindow *alertWindow = [[UIWindow alloc] initWithFrame:CGRectMake(200,0, 80, 20)];
        alertWindow.windowLevel = UIWindowLevelAlert;
        [alertWindow addSubview:messageNotiView];
        [alertWindow makeKeyAndVisible];
        [self.window addSubview:alertWindow];
    }
    else {
        self.window.windowLevel = UIWindowLevelAlert;
        messageNotiView.frame = CGRectMake(205,0, 80, 20);
        [self.window addSubview:messageNotiView];
    }

}

- (void)closeMesageStatusBarAlert {
    [messageNotiView setHidden:YES];
    messageNotiView = nil;
}


- (void)userDidLogout {
    [[UserSession shareUserSession] cleanSession];
    [self performSelectorOnMainThread:@selector(goToLoginView) withObject:nil waitUntilDone:YES];
}

- (void)goToLoginView {
    [self.navigationController popToRootViewControllerAnimated:NO];
    [self.navigationController pushViewController:_loginViewController animated:YES];
}


- (IBAction)messageAlertViewOnStatusBarDidClick:(id)sender {
    NSLog(@"message clicked");
    [self closeMesageStatusBarAlert];
    UIViewController *currentVc = self.navigationController.topViewController;
    if ([currentVc isKindOfClass:NSClassFromString(@"OneToOneChatViewController")] || [currentVc isKindOfClass:NSClassFromString(@"ChatListViewController")]) {
        return;
    }
    UIViewController *vc = [[NSClassFromString(@"ChatListViewController") alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

//{
//    content = "vk-Test0302_1";
//    extras =     {
//    };
//}
- (void)networkDidReceiveMessage:(NSNotification *)notification {
    NSDictionary * userInfo = [notification userInfo];
    NSString *title = [userInfo valueForKey:@"title"];
    NSString *content = [userInfo valueForKey:@"content"];
    NSDictionary *extras = [userInfo valueForKey:@"extras"];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
    NSLog(@" ---- push recieved\n %@",userInfo);
    NSLog(@"%@",[NSString stringWithFormat:@"收到消息\ndate:%@\ntitle:%@\ncontent:%@", [dateFormatter stringFromDate:[NSDate date]],title,content]);
    
    [self getMessagesFromServerOnBackground];
}

- (void)tagsAliasCallback:(int)iResCode tags:(NSSet*)tags alias:(NSString*)alias {
    NSLog(@"rescode: %d, \ntags: %@, \nalias: %@\n", iResCode, tags , alias);
}

#pragma mark - Public Methors
- (void)setToolbarHidden:(bool)isHidden {
#if ShowToolbarInWindow == 1
    self.gfToolbar.view.hidden = isHidden;
#endif
}

- (void)submitArticleInBackground {
    
}

- (void)checkNewVersion:(bool)needNotAlert {
    if (needNotAlert) {
        [SVProgressHUD showWithStatus:@"正在检查更新..."];
    }
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:app_Version,@"version",@"ios",@"platform", nil];
    [[AppsEngine shareAppsEngine] submitRequest:@"gfCheckVersion" param:params onCompletion:^(id jsonResponse) {
        [SVProgressHUD dismiss];
        if ([[jsonResponse objectForKey:@"newVersion"] integerValue]) {
            //有更新
            NSDictionary *updateContent = [jsonResponse objectForKey:@"content"];
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"发现新版本提示" message:[updateContent objectForKey:@"content"] delegate:self cancelButtonTitle:@"下次再提醒我" otherButtonTitles:@"马上升级", nil];
            [alert show];
        }
        else {
            if (needNotAlert) {
                [SVProgressHUD showSuccessWithStatus:@"已是最新版"];
            }
            else{
                NSLog(@"已是最新版");
            }
        }
    } onError:^(NSError *error) {
        [SVProgressHUD dismiss];
        NSLog(@"查询升级失败...");
    } method:@"GET"];
}

#pragma mark - 发表文章--上传图片
//- (void)setImageUpoadQueueDelegate:(id<ImageUploadQueueDelegate>)imageUpoadQueueDelegate {
//    self.imageUpoadQueueDelegate = imageUpoadQueueDelegate;
//}

- (void)uploadImageWithArray:(NSArray*)arr saveNameList:(NSArray*)arrName submitToSinaPaarms:(NSMutableDictionary*)paramsSina{
    if (isUploadQueueBusy) {
        if (!arrWaitingToUpload) {
            arrWaitingToUpload = [[NSMutableArray alloc] init];
        }
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:arr,@"ALSetPhotos",arrName,@"QiniuSavedName",paramsSina,@"ParamsToSina", nil];
        if (dict) {
            [arrWaitingToUpload addObject:dict];
        }
        return;
    }
    uploadImageIndex = 0;
    dispatch_queue_t SerialDispatchUploadImageQueue = dispatch_queue_create("PublishArticle_UploadImage_SerialQueue", NULL);
    for (int j = 0; j < [arr count]; j++) {
        isUploadQueueBusy = YES;
        dispatch_async(SerialDispatchUploadImageQueue, ^{
            if (uploadImageIndex >= [arr count]) {
                return;
            }
            NSString *imgPath = [arr objectAtIndex:uploadImageIndex];
            uploadDone = NO;
            if ([imgPath stringByMatching:@"GF-Document:"]) {
                imgPath = [imgPath stringByReplacingOccurrencesOfString:@"GF-Document:" withString:@""];
                if ([imageUploaderSerialQueue uploadImage:imgPath]) {
                    //上传图片成功
                    NSLog(@"-----------PublishAirticleViewController-uploadPhotos \n photo upload success \n local:%@ \n qiniu:%@---------------",imgPath,[arrName objectAtIndex:uploadImageIndex]);
                }
            }
            else {
                //这是相册的文件
                ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
                NSURL *url=[NSURL URLWithString:imgPath];
                [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset)  {
                    UIImage *image=[UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
                    NSString* fPath = saveAndResizeImage(image, [[arrName objectAtIndex:uploadImageIndex] lastPathComponent],640);
                    if ([imageUploaderSerialQueue uploadImage:fPath]) {
                        //上传图片成功
                        NSLog(@"-----------PublishAirticleViewController-uploadPhotos \n photo upload success \n local:%@ \n qiniu:%@---------------",fPath,[arrName objectAtIndex:uploadImageIndex]);
                    }
                }failureBlock:^(NSError *error) {
                    NSLog(@"error=%@",error);
                    NSLog(@"-----------PublishAirticleViewController-uploadPhotos \n photo upload success \n local:%@ \n qiniu:%@---------------",[arr objectAtIndex:uploadImageIndex],[arrName objectAtIndex:uploadImageIndex]);
                }
                 ];
            }
            [self waitFinish];
            
            //传完最后一张
            if (uploadImageIndex + 1 >= [arr count]) {
                //重传失败的图片
                if (arrForFialToUploadImages && [arrForFialToUploadImages count] > 0) {
                    NSMutableArray *arrP = [[NSMutableArray alloc] init],*arrN = [[NSMutableArray alloc] init];
                    for (int k = 0; k < [arrForFialToUploadImages count]; k++) {
                        int failIndex = [[arrForFialToUploadImages objectAtIndex:k] intValue];
                        if (failIndex < [arr count] && [arr objectAtIndex:failIndex] && [arrName objectAtIndex:failIndex]) {
                            [arrP addObject:[arr objectAtIndex:failIndex]];
                            [arrN addObject:[arrName objectAtIndex:failIndex]];
                        }
                    }
                    [arrForFialToUploadImages removeAllObjects];
                    isUploadQueueBusy = NO;
                    retryCounter++;
                    if (retryCounter >= 3) {
                        return;
                    }
                    [self uploadImageWithArray:arrP saveNameList:arrN submitToSinaPaarms:paramsSina];
                }
                else {
                    //全部上传成功
                    [self endBackgroundUpdateTask];
                    [self submitResultToSina:paramsSina];
                    isUploadQueueBusy = NO;
                    
                    //查看上传队列
                    if ([arrWaitingToUpload count] > 0) {
                        NSDictionary *dict = [arrWaitingToUpload firstObject];
                        if (dict) {
                            [arrWaitingToUpload removeObject:dict];
                            [self uploadImageWithArray:[dict objectForKey:@"ALSetPhotos"] saveNameList:[dict objectForKey:@"QiniuSavedName"] submitToSinaPaarms:[dict objectForKey:@"ParamsToSina"]];
                        }
                    }
                }
            }
        });
    }

}

- (void)uploadSuccess:(NSString *)filePath ret:(NSDictionary *)ret {
    uploadImageIndex++;
    uploadDone = YES;
    if ([self.imageUpoadQueueDelegate respondsToSelector:@selector(ImageUploadQueueItemSuccess:ret:)]) {
        [self.imageUpoadQueueDelegate ImageUploadQueueItemSuccess:filePath ret:ret];
    }
}

- (void)uploadFail:(NSString *)filePath error:(NSError *)error {
    //记录失败的图片
    [arrForFialToUploadImages addObject:[NSNumber numberWithInt:uploadImageIndex]];
    uploadImageIndex++;
    uploadDone = YES;
    
    if ([self.imageUpoadQueueDelegate respondsToSelector:@selector(ImageUploadQueueItemFail:error:)]) {
        [self.imageUpoadQueueDelegate ImageUploadQueueItemFail:filePath error:error];
    }
}

- (void)imageUploaderProcessUpdated:(NSString *)filePath percent:(float)percent {
    if ([self.imageUpoadQueueDelegate respondsToSelector:@selector(ImageUploadQueueItemProcessUpdated:percent:)]) {
        [self.imageUpoadQueueDelegate ImageUploadQueueItemProcessUpdated:filePath percent:percent];
    }
}

- (void) waitFinish {
    int waitLoop = 400;
    while (!uploadDone && waitLoop > 0) // Wait for 400 seconds.
    {
        //        NSLog(@"Waiting for the result...");
        sleep(1);
        waitLoop--;
    }
    if (waitLoop <= 0) {
        //上传失败
        NSLog(@"Failed to receive expected delegate messages.");
        [arrForFialToUploadImages addObject:[NSNumber numberWithInt:uploadImageIndex]];
    }
}

#pragma mark - 后台上传图片
- (void)beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void)endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

- (void)submitResultToSina:(NSMutableDictionary*)_dict {
    if (!_dict) {
        return;
    }
    [[AppsEngine shareAppsEngine] submitRequest:@"gfPublishCircleArticle" param:_dict onCompletion:^(id jsonResponse) {
        if ([jsonResponse objectForKey:@"status"] && [[jsonResponse objectForKey:@"status"] isEqualToString:@"success"]) {
            NSLog(@"提交成功!");
            [SVProgressHUD showSuccessWithStatus:@"提交成功!"];
            [[NSNotificationCenter defaultCenter] postNotificationName:Notification_Article_Published object:nil];
        }
        else {
            [SVProgressHUD showErrorWithStatus:@"发表文章失败"];
            NSLog(@"-------------  提交失败!\n reason:%@",[jsonResponse objectForKey:@"reason"]);
        }
    } onError:^(NSError *error) {
        NSLog(@"------------- 无法连接网络!\nreason:%@",error);
    } method:@"GET"];
}


@end
